#include "tcpclientsocket.h"

QString TcpClientSocket::getUserName() const
{
    return userName;
}

void TcpClientSocket::setUserName(const QString &newUserName)
{
    userName = newUserName;
}

Message* TcpClientSocket::readMessage()
{
    auto b = readAll();
    return Message::fromByteArray(b);
}

void TcpClientSocket::writeMsg(Message *msg)
{
    write(msg->toByteArray());
}


TcpClientSocket::TcpClientSocket(QObject *parent): QTcpSocket{parent}
{
    connect(this, &TcpClientSocket::readyRead, this, &TcpClientSocket::dataReceived);
    connect(this, &TcpClientSocket::disconnected, this, [=](){
        emit disConnected(this);
    });
}

void TcpClientSocket::dataReceived()
{
    if (bytesAvailable() >0){
        Message* msg = readMessage();

        if (msg->getCmdType() == CmdType::Login){
            userName = msg->getBody();
        }
        emit dataReady(msg, this);
    }

}
